namespace :gumi do
  desc "get gumi@bilibili data"
  task :get_data => :environment do
     base_url = "http://www.bilibili.tv/sppage/"
     ad_recommend = "ad-recommend-345-"
     tag_hot = "tag-hot-345-"
     http = Net::HTTP::Persistent.new(nil, (PROXY ? URI.parse(PROXY) : nil))
     #集计范围数组
     wids = []
     #ad-recommend 4 page recently
     (1..4).each do |i|
       tmp_page = Timeout.timeout(10){http.request(URI.parse(base_url + ad_recommend + i.to_s + ".html"))}
       noko = Nokogiri::HTML(tmp_page.plain_body, nil, 'utf-8')
        divs = noko.css("div.po")
       puts "#{i}: #{divs.size}"
        divs.each do |po|
            po_href = po.search("a").first.get_attribute("href")
          work = Work.find_by_wid(po_href.delete("/video/av").to_i)
          if work && work.ac_type_id == 13 && work.part_count <= 2
            wids << work.wid
          end
        end
     end
     #tag_hot 77 page recently
     (1..77).each do |i|
       tmp_page = Timeout.timeout(10){http.request(URI.parse(base_url + tag_hot + i.to_s + ".html"))}
       noko = Nokogiri::HTML(tmp_page.plain_body, nil, 'utf-8')
        divs = noko.css("div.po")
       puts "#{i}: #{divs.size}"
        divs.each do |po|
          po_href = po.search("a").first.get_attribute("href")
          work = Work.find_by_wid(po_href.delete("/video/av").to_i)
          if work && work.ac_type_id == 13 && work.part_count <= 2
            wids << work.wid
          end
        end
     end
     File.open(%[#{Rails.root}/config/_gumi.yml],"w"){ |io| YAML.dump wids.uniq, io }
  end

  desc "stat gumi@bilibili data"
  task :stat => :environment do
    id2 = 861
    wids = YAML.load(File.open "#{Rails.root}/config/_gumi.yml")
    Result = Results::R902
    weekly_results = WeeklyResult.stat(0, id2, wids, 'some')
    doc = File.new("#{Rails.root}/_gumi_list.csv", 'w')
    str = "总分排名,总分,id,投稿时间,标题,点击,评论,收藏,弹幕,封面\n"
        weekly_results.each do |r|
            str << %(#{r['point_rank']},#{r['point']},)
            str << %(#{r.work.wid},#{r.work.cdate.strftime("%Y年%m月%d日 %H:%M")},"#{r.work.name.gsub(/"/, '""')}",)
            str << %(#{r.clicks},#{r.comments},)
            str << %(#{r.stows},)
            str << %(#{r.danmu},)
            str << %(#{r.work.pic_path})
            str << "\n"
        end
        doc.write str
  end
end


